package com.android.jr_infraredcamera.utils

import android.content.Context.USB_SERVICE
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
import com.android.jr_infraredcamera.UsbRtmpFragment
import com.android.jr_infraredcamera.base.App
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException
import java.lang.Exception
import java.nio.ByteBuffer

/**
 * @author 战神族灬小火
 * @date 2025/2/26
 * @description
 */
class UsbSerialPortUtils {
    companion object {
        private const val TAG = "===UsbSerialPortUtils==="

        private val instant by lazy { UsbSerialPortUtils() }

        fun getInstance(): UsbSerialPortUtils {
            return instant
        }
    }

    private var usbManager: UsbManager = App.mContext.getSystemService(USB_SERVICE) as UsbManager
    private var port: UsbSerialPort? = null
    private var usbIoManager: SerialInputOutputManager? = null


    fun openSerial(device: UsbDevice) {
        if (!Config.isUsbSerial) return
        // 注意：需先添加 usb-serial-for-android 库依赖
        port = UsbSerialProber.getDefaultProber().probeDevice(device).ports[0]
        try {
            port?.open(usbManager.openDevice(device))
            port?.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)

            Log.d(TAG, "串口打开成功")
        } catch (e: Exception) {
            Log.e(TAG, "串口打开失败", e)
        }
    }

    /**
     * 初始化
     */
    fun initUsb(callBack: SerialInputOutputManager.Listener) {
        if (!Config.isUsbSerial) return
        Thread {
            val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)
            if (availableDrivers.isEmpty()) {
                return@Thread
            }
            // Open a connection to the first available driver.
            val driver = availableDrivers[0]
            val connection = usbManager.openDevice(driver.device)
                ?: // add UsbManager.requestPermission(driver.getDevice(), ..) handling here
                return@Thread
            //结果返回出去
            port = driver.ports[0] // Most devices have just one port (port 0)


            port?.open(connection)
            port?.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
//            usbIoManager = SerialInputOutputManager(port, callBack)
//            usbIoManager?.start()


            Log.e(
                TAG,
                "initUsb: ======${usbIoManager?.readTimeout}====${usbIoManager?.readBufferSize}",
            )


            /*  withContext(Dispatchers.IO) {
                  val byteArray = ByteArray(1024)  // 设置合适的字节数组大小
                  val timeout = 1000  // 设置超时时间为 1 秒
                  while (port != null) {
                      try {
                          // 从串口读取数据
                          val bytesRead = port?.read(byteArray, timeout) ?: -1
                          if (bytesRead > 0) {
                              // 处理读取到的字节数据
                              val data = byteArray.copyOf(bytesRead)
                             // processData(data)
                              Log.e(TAG, "initUsb: ====${data.toHexString(true)}")

                          }
                      } catch (e: IOException) {
                          e.printStackTrace()  // 异常处理
                      }

                  }
              }*/
        }.start()

    }

    /**
     * 发送
     */
    fun sendData(data: ByteArray) = CoroutineScope(Dispatchers.IO).launch {
        if (!Config.isUsbSerial) return@launch
        Log.e(TAG, "sendData: ======发送的数据===${data.toHexString(true)}")
        port?.write(data, 3000)
    }


    suspend fun writeAndReadData(data: ByteArray, readSize: Int): ByteArray? =
        withTimeoutOrNull(3000) {
            if (!Config.isUsbSerial) return@withTimeoutOrNull null
            Log.e(TAG, "sendData: ======发送的数据===${data.toHexString(true)}===$readSize")
            port?.write(data, 0)
            if (readSize > 0) {
                val byteArray = ByteArray(readSize)


                val len = port?.read(byteArray, 2500)

                if (len != null) {
                    if (len > 0) {
                        return@withTimeoutOrNull byteArray
                    } else {
                        Log.d(TAG, "writeAndReadData: ===无数据")
                        return@withTimeoutOrNull byteArrayOf()
                    }
                } else {
                    Log.d(TAG, "writeAndReadData: ===let=null")
                    return@withTimeoutOrNull byteArrayOf()
                }

            } else {
                Log.d(TAG, "writeAndReadData: ===readSize=0")
                return@withTimeoutOrNull byteArrayOf()
            }

        }

    fun close() = CoroutineScope(Dispatchers.IO).launch {
        if (!Config.isUsbSerial) return@launch
        try {
            port?.close()
            usbIoManager?.stop()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}